package com.xigua.basicsAndApplication;

import redis.clients.jedis.*;

import java.io.IOException;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: 使用zset实现滑动窗口限流
 * @date 2022/1/1522:23
 */
public class SimpleRateLimiter {
    private Jedis jedis;
    private static JedisPool jedisPool;

    static {

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(10);
        config.setMaxWaitMillis(30000);
        jedisPool = new JedisPool(config,"120.76.116.216",6379,3000,"xg123456");

    }

    public SimpleRateLimiter(Jedis jedis) {
        this.jedis = jedis;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        Jedis jedis = jedisPool.getResource();
        SimpleRateLimiter simple = new SimpleRateLimiter(jedis);
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 6; j++) {
                System.out.println(simple.isActionAllowed("xigua", "reply", 60, 5));
            }
            Thread.sleep(60000);
        }
    }

    public boolean isActionAllowed(String userId,String actionKey,int period,int maxCount) throws IOException {
        String key = String.format("hist:%s:%s", userId, actionKey);
        long nowTs = System.currentTimeMillis();
        Pipeline pipelined = jedis.pipelined();
        pipelined.multi();
        pipelined.zadd(key,nowTs,""+nowTs);
        pipelined.zremrangeByScore(key,0,nowTs-period*1000);
        Response<Long> count = pipelined.zcard(key);
        pipelined.expire(key,period+1);
        pipelined.exec();
        pipelined.close();
        return count.get() <= maxCount;
    }



}
